---
title: "Security Council Membership Data"
author: "Gina Reynolds and Matt Winters"
output: pdf_document
---

This file is used in replicating findings for "Foreign Aid Funnel? Placebo-Based Assessment of Aid Flows to  Non-Permanent U.N. Security Council Members" by Evangeline Reynolds (University of Illinois) and Matthew Winters (University of Illinois). 


The U.N. Security Council data come from the U.N.'s website ``Countries Elected Members of the Security Council", <http://www.un.org/en/sc/members/elected.asp>, accessed December 12, 2014.  

Read in Data
----

```{r}
text <- readLines("./01RawData/UNSC - RawDataUNSCnonPerm.txt", encoding="UTF-8")
head(text)
tail(text)
```


```{r}
text0=iconv(text, "", "ASCII", "byte")
library(stringr)
text1= str_replace_all(text0, " , ", "/")
head(text1)
text2= str_replace_all(text1, " <e2><80><93> ", "-")
head(text2)
text3= gsub(" $","", text2, perl=T)
head(text3)
tail(text3)
```


```{r}
#Because we'll use the dash "-" as a marker, 
#we need to replace this in country names: 
text3=str_replace_all(text3, "Guinea-Bissau", "Guinea Bissau")
```

Special cases
-----

We delete Saudia Arabia - which did not take it's seat.  See the note: ``(declined to take the seat - see A/68/599)''

```{r}
length(text3)
text3=text3[!substr(text3,1,12)=="Saudi Arabia"]
length(text3)
```

```{r, addreturns}
text4=text3  
for (i in 1:length(text4)){
  text4[i]=
    if(
       any(substring(text4[i],1,1)==c(1:9))|
       grepl("see", text4[i])|
       grepl("Perm", text4[i])
       ){
     paste(str_replace_all(text4[i]," ",""),"\r\n",sep="")    
    }
  else{
     paste(text4[i], "/") }
} 

head(text4)
tail(text4)

long=c()
for (i in 1:length(text4)){
  long=paste(long,text4[i], sep="")
} 

length(long)
substr(long, 1,100)

writeLines(long, "Temp.txt")

```



```{r}
text5 <- readLines("Temp.txt")
head(text5)
tail(text5)
file.remove("Temp.txt")
```

Parse data
-----

```{r}
TenuresData=data.frame(CountryName=character(), TwoYearTenure=character())
TenuresData


for (i in 1:length(text5)){
EachCountry=strsplit(text5[i],split="/")
if(length(EachCountry[[1]])>1){
for (j in 2:length(EachCountry[[1]])){
  TenuresData=rbind(TenuresData, 
                    data.frame(CountryName=EachCountry[[1]][1],
                                            TwoYearTenure=EachCountry[[1]][j]))
}
}
}
head(TenuresData)
TenuresData$SCYearOne=as.numeric(substr(TenuresData$TwoYearTenure,1,4))
TenuresData$SCYearTwo=as.numeric(substr(TenuresData$TwoYearTenure,6,9))
```


Correction to Raw Data: 
One case (East Germany) is missing from the U.N. website
---
```{r}

OneCase=data.frame(CountryName="East Germany", 
                   TwoYearTenure="1980-1981", 
                   SCYearOne=1980, 
                   SCYearTwo=1981)

TenuresData=rbind(TenuresData, OneCase)
tail(TenuresData)  #East Germany has been added.
```

Correction to Raw Data
---

Before 1990, `Germany' should actually be ``West Germany"
---
```{r}
TenuresData$CountryName=as.character(TenuresData$CountryName)
TenuresData[TenuresData$CountryName=="Germany ",]
TenuresData$CountryName[TenuresData$CountryName=="Germany "& 
                          TenuresData$SCYearOne<1990]="West Germany"

TenuresData[TenuresData$CountryName=="West Germany",]
```



```{r}
TenuresData$CountryName =str_trim(TenuresData$CountryName) #trims off trailing or leading spaces.
setwd("./000MyCountryCoder/") #For chunk temporarily resets locaction
source("countrycode2.R")
TenuresData$StandardName=FavoriteCountryName(TenuresData$CountryName)
dim(TenuresData)
head(TenuresData)
```



Add variable for the year after the Security Council tenure
---

This variable is used frequently in the UNSC-aid papers, since the foreign aid quid-pro quo can take a while to complete.

```{r}
options(width=90)
table(is.na(TenuresData$SCYearTwo))
#This is not always two years after the first year on the council 
#since some tenures are just one year long
TenuresData$YearAfterSCMembership=ifelse(!is.na(TenuresData$SCYearTwo), 
                                         TenuresData$SCYearTwo+1, 
                                         TenuresData$SCYearOne+1 )
head(TenuresData)
```


Save Country-Tenure Data
---
```{r}
write.csv(TenuresData, "03_UNSC - SCTenuresData.csv")
save(TenuresData, file="03_UNSC - SCTenuresData.RData")

```

Create TSCS Data 
===

Create Country-Year Backbone
----
We include all countries that have been U.N. members and do a wide-to-long transformation with UNSC year info.

```{r}
Year1=data.frame(StandardName=TenuresData$StandardName, 
                 Year=        as.numeric(TenuresData$SCYearOne),
                 WhichTenureYear=1)
Year2=data.frame(StandardName=TenuresData$StandardName, 
                 Year=        as.numeric(TenuresData$SCYearTwo),
                 WhichTenureYear=2)
Year2=Year2[!is.na(Year2$Year),] #several cases where the country does not stay for a second year
Year3=data.frame(StandardName=TenuresData$StandardName, 
                 Year=        as.numeric(TenuresData$YearAfterSCMembership),
                 WhichTenureYear=3)

CountryCouncilYears=rbind(Year1, Year2, Year3)
head(CountryCouncilYears)
tail(CountryCouncilYears)
table(CountryCouncilYears$WhichTenureYear)

CountryCouncilYears=CountryCouncilYears[CountryCouncilYears$Year!=2016, ]
```


Save Long Data
---

```{r}
# str(LongSC)
#write.csv(LongSC, "03_UNSCMembTenureLong.csv")
#save(LongSC, file="03_UNSCMembTenureLong.RData")
```


Plot Membership Years
----

```{r, plotSC1, fig.height=11}
TenuresData$StandardName=factor(as.character(TenuresData$StandardName),                                levels=unique(TenuresData$StandardName)[length(unique(TenuresData$StandardName)):1])

str(TenuresData)

max(na.omit(TenuresData$SCYearTwo))
par(mar=c(2.1,2.1,2.1,12))
plot(c(1946,max(na.omit(TenuresData$SCYearTwo))), 
     c(1,max(as.numeric(TenuresData$StandardName))), 
     pch="",
     axes=FALSE,
     xlab="Year",
     ylab=""
     )

abline(v=1965, col="lightgrey", lty=2)
abline(h=c(1:length(levels(TenuresData$StandardName))), col="lightgrey")

axis(1 )
axis(4, at=c(1:length(levels(TenuresData$StandardName))),
     labels=levels(TenuresData$StandardName), las=2, cex.axis=0.3, col="white")

points(TenuresData$SCYearOne,
       as.numeric(TenuresData$StandardName), 
       cex=.7)
points(TenuresData$SCYearTwo,
       as.numeric(TenuresData$StandardName), 
       cex=.7)
```





